import React from 'react'
import cx from 'classnames'
import style from './style'
import Link from '../link'
import { Button } from 'sq-ui'
import styleDialog from './style.dialog'
import { connect } from 'react-redux'
import util from '../../util';

const div = React.DOM.div

@connect(({app}) => ({app}), null)
export default
class ModalPortal extends React.Component {

  state = {
    afterOpen: false,
    beforeClose: false
  }

  static defaultProps = {
    closeTimeoutMS: 150,
    shouldCloseOnOverlayClick: false // 是否允许点击遮罩层关闭
  }

  shouldBeClosed() {
    return !this.props.active && !this.state.beforeClose
  }

  handleOverlayClick() {
    if (this.props.shouldCloseOnOverlayClick) {
      this.closeOverlay()
    }
  }

  closeOverlay() {
    if (this.ownerHandlesClose())
      this.requestClose();
  }

  requestClose() {
    this.props.onRequestClose()
  }

  ownerHandlesClose() {
    return this.props.onRequestClose()
  }

  handleKeyDown(e) {
    // esc
    if (e.which == 27) {
      this.requestClose()
    }
  }


  componentDidMount() {
    if (this.props.active) {
      this.open();
    }
  }

  componentWillReceiveProps(props) {
    if (props.active && !this.props.active) {
      this.open()
    } else if(!props.active && this.props.active) {
      this.close()
    }
  }

  // clear timeout
  componentWillUnmount() {
    clearTimeout(this.closeTimer)
  }

  close() {
    this.setState({
      beforeClose: true,
      afterOpen: false
    }, () => {
      this.closeTimer = setTimeout(::this.closeWithoutTimeout, this.props.closeTimeoutMS)

      document.body.className = document.body.className.replace(/(\s*has\-modal)/, '');
    })
  }

  closeWithoutTimeout() {
    this.setState({
      beforeClose: false
    })
  }

  open() {
    setTimeout(() => {
      this.setState({
        afterOpen: true
      }, () => {
        document.body.className = cx(document.body.className, 'has-modal');
      })
    } ,100)
  }

  render() {
    if (this.shouldBeClosed()) return div()
    let { actions=[], app } = this.props
    const { isNaviOrg } = (app||{org:{}}).org;
    return (
      <div className={cx({
        [style.root]: true
      })}>
        <div 
          ref='overlay' 
          onClick={::this.handleOverlayClick}
          className={cx({
            [style.overlay]: true,
            [style.active]: this.state.afterOpen
          })}>
        </div>
        <div ref={el => {
          if (el && !el.load) {
            el.load = true;
            el.addEventListener('scroll', () => {
              util.bus.emit('page:scroll');
            });
          }
        }} className={cx(style['scroll'], {
          [style['has-guide']]: isNaviOrg,
        })}> 
          <div 
            onClick={e => e.stopPropagation()}
            onKeyDown={::this.handleKeyDown}
            className={cx({
              [style.content]: true,
              [style.afterOpen]: this.state.afterOpen
            })}
            ref='content'
          >
  					<div 
  						className={cx({
  							[this.props.className]: this.props.className,
  							[style.main]: true,
  							[style.alert]: this.props.alert
  						})}
  					>
  						<div className={style.body}>
                <div className={cx({
                  [styleDialog.root]: true,
                  [styleDialog.hasAction]: this.props.actions
                })}>
                  {
                    this.props.close?
                    <Link data-role="close" icon="close" onClick={::this.closeOverlay} size="24" className={styleDialog.close}/>: null
                  }
                  <div className={cx({
                    [styleDialog.body]: true,
                    [styleDialog.twoColumn]: this.props.twoColumn
                  })}>
                    { 
                      this.props.title? (
                        <div data-role="dialog-title">
                          {
                            this.props.title
                          }
                          <span 
                            className={style['dialog-close-icon']}
                            onClick={::this.props.onRequestClose}
                          >x</span>
                        </div>
                      ): null
                    }
                    { 
                      React.Children.map(this.props.children, child => React.cloneElement(child, {
                        'data-role': "dialog-body"
                      }))
                    }
                    {
                      actions.length? (
                        <div className={styleDialog.actions}>
                        {
                          actions.map((action, i) => {
                            if (typeof action === 'function') {
                              return (
                                <Button 
                                  blue
                                  disabled={this.props.isSubmitDisabled}
                                  style={{ width: '70px', height: '30px' }}
                                  key={i} 
                                  label='确定' 
                                  onClick={action}
                                  {...others}
                                />
                              )
                            }
                            if (action === 'cancel') {
                              return (
                                <Button 
                                  grey
                                  style={{ width: '70px', height: '30px', marginRight: '10px' }}
                                  key={i} 
                                  label='取消' 
                                  onClick={::this.props.onRequestClose}
                                  {...others}
                                />
                              )
                            }
                            const { label, handler, ...others } = action
                            return (
                              <Button 
                                blue
                                style={{ width: '70px', height: '30px' }}
                                key={i} 
                                label={label} 
                                onClick={handler}
                                {...others}
                              />
                            )
                          })
                        }
                        </div>
                      ): null
                    }
                  </div>
                </div>
  						</div>
  					</div>
          </div>
        </div>
      </div>
    )
  }
}
